// src/utils/packageManager.ts
import shell from 'shelljs';
import { logger } from './logger';

export interface PackageManager {
  install: (cwd?: string) => boolean;
  run: (script: string, cwd?: string) => boolean;
}

// 检测可用的包管理器
export const detectPackageManager = (): 'npm' | 'yarn' | 'pnpm' => {
  if (shell.which('pnpm')) {
    return 'pnpm';
  } else if (shell.which('yarn')) {
    return 'yarn';
  } else {
    return 'npm';
  }
};

// 创建包管理器实例
export const createPackageManager = (): PackageManager => {
  const pm = detectPackageManager();
  logger.info(`检测到包管理器: ${pm}`);
  
  return {
    install: (cwd?: string) => {
      logger.info(`正在安装依赖 (${pm} install)...`);
      const command = cwd ? `cd ${cwd} && ${pm} install` : `${pm} install`;
      return shell.exec(command).code === 0;
    },
    
    run: (script: string, cwd?: string) => {
      logger.info(`执行脚本: ${pm} run ${script}`);
      const command = cwd ? `cd ${cwd} && ${pm} run ${script}` : `${pm} run ${script}`;
      return shell.exec(command).code === 0;
    }
  };
};